#include<iostream>
#include<cstring>
#include<unistd.h>

#include"common3.hpp"

using namespace std;

int main()
{
    //服务端：读取
    shm s(SERVER);

    char * start= (char*)s.getStart();
    int wfd =s.getWFD();
    int rfd =s.getRFD();

    const char* str ="yes";

    // 因为是服务端先启动，所以直接先向管道中发出 yes 的指令
    write(wfd, str, strlen(str));

    char buff[64];

    while(true)
    {
        //等待客户端发出操作命令
        int n =read(rfd,buff,sizeof(buff)-1);
        buff[n] = 0;

        if(n>0)
        {
            if(strcasecmp(str,buff) == 0)
            {
                //客户端允许服务端进行读取
                int i = 0;
                while(start[i])
                {
                    buff[i] = start[i];
                    i++;
                }
                buff[i] = 0;

                printf("server read# %s\n",buff);

                if(strcasecmp("exit",buff) == 0)
                break;

                //读取完成，通知客服端写入
                write(wfd,str,strlen(str));
            }
        }
        else if( n == 0)
        {
             cerr << "客户端未从管道中读取到数据" << endl;
        }

        else
        {
            cerr << "读取异常" << endl;
            break;
        }
    }
    return 0;
}